
//Check imei number
function checkImeiNumber(){
	if(typeof localStorage["imeiNumber"]!='undefined'){
		var imeiNumber=JSON.parse(localStorage["imeiNumber"]);
	}else{
		var imeiNumber=0;
	}
	var randomPoz="";
	var alphaPoz="";
	var numimei_number="";
	var alphaimei_number="";
	var i=0;
	var numbersSet="0123456789";
	var albetsSet="abcdefghijklmnopqrstuvwxyz";
	var imei_number="";
	if(imeiNumber!=0){
		imei_number=imeiNumber;
		checkUserInfo();
	}else{
		for(i=0;i<=4;i++){
			 randomPoz = Math.floor(Math.random() * numbersSet.length);
			 numimei_number += numbersSet.substring(randomPoz,randomPoz+1);
		}
		for(i=0;i<=4;i++){
			 alphaPoz = Math.floor(Math.random() * albetsSet.length);
			 alphaimei_number += albetsSet.substring(alphaPoz,alphaPoz+1);
		}
		var imei_number=numimei_number+alphaimei_number;
		$.ajax({
			type		:	'PUT',
			url			:  	webServiceUrl+'submitwinner/'+imei_number,
			dataType	: 	"json",
			data		:	{imei_number:imei_number},
			success: function(data){
				$('#registerReload').html('');
				if(data.value==2){
					checkImeiNumber();
				}else if(data.value==1){
					localStorage.setItem( 'imeiNumber', JSON.stringify(imei_number));
					checkUserInfo();
				}
			}
		});	
    }
}


// check user detailes

function checkUserInfo(){
var imeiNumber=JSON.parse(localStorage["imeiNumber"]);
$('#registerReload').html('<img src="images/ajax-loader.gif"/>');
	$.ajax({
		type		:	'GET',
		url			:  	webServiceUrl+'admin',
		dataType	: 	"json",
		success: function(datta){
			$('#registerReload').html('');
			$.ajax({
				type		:	'GET',
				url			:  	webServiceUrl+'Register/'+imeiNumber+'-'+datta.success_per_day,
				dataType	: 	"json",
				success: function(dataa){
					if(datta.value==1){
					var objj = eval("(" + datta.data + ")");
						$.each(objj, function (indexx,Objectt) {
							$('#win_message').html(Objectt.win_message);
							$('#win_message_arabic').html(Objectt.win_message_arabic);
							$('#win_logo').html(Objectt.win_logo);
							$('#reg_image').html(Objectt.reg_image);
							$('#chance_per_day').val(Objectt.numberof_chance_per_day);
							if(dataa.value==0){
								var obj = eval("(" + dataa.checkStatus + ")");
								$.each(obj, function (index,Object) {
									if(Object.lifetime_wins<Objectt.life_time_wins){
										if(Object.numberof_coins>0){
											if(Object.chance_per_day!=Objectt.numberof_chance_per_day){
												if(Object.numberof_failure_attempts==Objectt.numberof_failure_attemts){
													loadBoxes(success);
												}else{
													loadBoxes(normal);
												}
											}else{
												setTimeout (function () {
													$('.pop_fix_bg_loader').hide();
													$('#container').fadeIn();
													$('#sorry_message_fb').show();
												}, 8000);
												
											}
										}else{
											setTimeout (function () {
													$('.pop_fix_bg_loader').hide();
													$('#container').fadeIn();
													$('#sorry_message').show();
													$('#sorry_message_p_arabic').html("Chances Completed.");
													$('#sorry_message_p').html("Chances Completed.");
											}, 8000);
											
										}
									}else {
										if(Object.chance_per_day!=Objectt.numberof_chance_per_day){
											if(Object.numberof_coins>0){
												loadBoxes(failure);
											}else{
												setTimeout (function () {
													$('.pop_fix_bg_loader').hide();
													$('#container').fadeIn();
													$('#sorry_message').show();
													$('#sorry_message_p_arabic').html("Chances Completed.");
													$('#sorry_message_p').html("Chances Completed.");
												}, 8000);
											}
										}else{
											setTimeout (function () {
												$('.pop_fix_bg_loader').hide();
												$('#container').fadeIn();
												$('#sorry_message_fb').show();
											}, 8000);
										}
									}
								});
							}else{
								setTimeout (function () {
									$('.pop_fix_bg_loader').hide();
									$('#container').fadeIn();
									$('#sorry_message').show();
									$('#sorry_message_p_arabic').html("لقد ربحت اليوم , حاول غدآ.");
									$('#sorry_message_p').html("You already won the game for the day. Try again next day.");
								}, 8000);
							}
						});	
					}
				}
			});
		}
	});
}

//Lost OR Won The Game

function gameWonLostFunction(winStatus){
var imeiNumber=JSON.parse(localStorage["imeiNumber"]);
var chance_per_day=$('#chance_per_day').val();
$('#registerReload').html('<img src="images/ajax-loader.gif"/>');
	$.ajax({
		type		:	'POST',
		url			:  	webServiceUrl+'entertoframe',
		dataType	: 	"json",
		data		:	{imei_number:imeiNumber,failed:winStatus,chance_per_day:chance_per_day},
		success: function(data){
			$('#registerReload').html('');
			if(data.value==1){
				if(winStatus==0){
					if(data.chanceCount==chance_per_day){
						$('#sorry_message_fb').show();
					}else{
						$('#sorry_message_chances').show();
						if(data.chanceCount == 1) {
							localStorage.setItem( 'time_delay', JSON.stringify(8000) );
						} else if(data.chanceCount == 2) {
							localStorage.setItem( 'time_delay', JSON.stringify(8000) );
						} else {
							localStorage.setItem( 'time_delay', JSON.stringify(8000) );
						}
						
						$('#sorry_message_p_chance').html('Try again you have '+(chance_per_day-data.chanceCount)+' chance remaining.');
						$('#sorry_message_p_chance_arabic').html('<b>حاول مرة أخرى. لا يزال لديك فرصة للفوز .</b>');
					}
				}else{
					$('#hurray_message').show();
					var win_message=$('#win_message').html();
					var win_message_arabic=$('#win_message_arabic').html();
					var win_logo=$('#win_logo').html();
					$('#hurray_p').html('<h2>HURRAY!!!</h2><p>We have our winner today!!</p><p>'+win_message+'</p><h3><a style="text-decoration: none;" href="javascript:void(0);" onclick="claimPrize()"><b style="color:#4E2507;">Touch here to claim your prize</b></a></h3>');
					$('#hurray_image').html('<img src="'+webImageUrl+win_logo+'"/>');
					$('#hurray_p_arabic').html('<h2>انت الفائز معنا</h2><h2>'+win_message_arabic+'</h2><h3><a style="text-decoration: none;" href="javascript:void(0);" onclick="claimPrize()"><b style="color:#4E2507;">:أنقر لإدخال بيانات الفائز</b></a></h3>');
				}
			}else if(data.value==2){
				$('#sorry_message_fb').show();
			}
		}
	});
}

// Share face book link then change status then play again.
function changeChanceStatus(){
var imeiNumber=JSON.parse(localStorage["imeiNumber"]);
$('#registerReload').html('<img src="images/ajax-loader.gif"/>');
	$.ajax({
		type		:	'PUT',
		url			:  	webServiceUrl+'entertoframe/'+imeiNumber,
		dataType	: 	"json",
		data		:	{imei_number:imeiNumber},
		success: function(data){
			$('#registerReload').html('');
			if(data.value==1){
				window.location=baseUrl;
			}
		}
	});
}
function playAgaine(){
	window.location=baseUrl;
}
function loadBoxes(state){
	//$('.pop_fix_bg_loader').show();
	for(var b=0; b<3;b++){
		if(state==normal){
			var randBox=getRandomInt(1,4);
			path = 'img/'+getSelectedItem(randBox)+'/';
			box_items[b]=randBox;
		}else if(state==success){
			path = 'img/'+getSelectedItem(1)+'/';
			box_items[b]=1;
		}else{
			if(b==0){
				var randBox=getRandomInt(1,2);
			}else{
				var randBox=getRandomInt(3,4);
			}
			path = 'img/'+getSelectedItem(randBox)+'/';
			box_items[b]=randBox;
		}
		if(b==0){
			images1=path;
			openBox(1,0,9);
		}else if(b==1){
			images2=path;
			openBox(2,0,9);
		}else{
			images3=path;
			openBox(3,0,9);
		}
	}
}

function preload(arrayOfImages) {
    $(arrayOfImages).each(function(){
        $('<img />')[0].src = this;
    });
}

function openBox(openBN,ready,totalB){
	var imagesPath="";
	if(openBN==1 && box1_open==0){
		imagesPath=images1;
		openCount++;
		box1_open=1;
		$('#box-'+openBN).flipbook({
			'start': 1,
			'end': totalB,
			'loop': 0,
			'fps': 10,
			'step': 1,
			'images': imagesPath+'/%d.png'
		});
	}else if(openBN==2 && box2_open==0){
		imagesPath=images2;
		openCount++;
		box2_open=1;
		$('#box-'+openBN).flipbook({
			'start': 1,
			'end': totalB,
			'loop': 0,
			'fps': 10,
			'step': 1,
			'images': imagesPath+'/%d.png'
		});
	}else if(openBN==3 && box3_open==0){
		imagesPath=images3;
		openCount++;
		box3_open=1;
		$('#box-'+openBN).flipbook({
			'start': 1,
			'end': totalB,
			'loop': 0,
			'fps': 10,
			'step': 1,
			'images': imagesPath+'/%d.png'
		});
	}
	if(ready==1){
		if(openCount==3){
			isGameWon();
		}
	}else{
		//if(openCount==3){
			openCount=0;
			box1_open=0;
			box2_open=0;
			box3_open=0;
			if(typeof localStorage["time_delay"]=='undefined'){
				localStorage.setItem( 'time_delay', JSON.stringify(8000) );
			} 
			var timeDelay = JSON.parse(localStorage["time_delay"]);
			setTimeout (function () {
				$('.pop_fix_bg_loader').hide();
				if(typeof localStorage["pop_value"]=='undefined'){
					$('#luck_message').show();
					localStorage.setItem( 'pop_value', JSON.stringify(1) );
				}
			}, timeDelay);
		//}
	}
 }
function getSelectedItem(item){
	if(item==diamonds){
		item_selcted="diamonds";
	}else if(item==knife){
		item_selcted="knife";
	}else if(item==coins){
		item_selcted="coins";
	}else if(item==pot){
		item_selcted="pot";
	}
	return item_selcted;
}
function isGameWon(){
	if((box_items[0]==box_items[1]) && (box_items[1]==box_items[2])){
		gameWonLostFunction(1);
	}else{
		gameWonLostFunction(0);
	}
}
function claimPrize(){
	$('#hurray_message').hide();
	var reg_image=$('#reg_image').html();
	$('#reg_image_form').html('<img src="'+webImageUrl+reg_image+'"/>');
	$('#won_box').show();
}
function submitUserDetails(){
	var flag=true;
	var name=$('#userName').val();
	var email=$('#userEmail').val();
	var phone=$('#userPhone').val();
	
	if(name==""){
		$('#errorUsername').html('Required');
		flag=false; 
	}else{
		$('#errorUsername').html('');
	}
	if(email==""){
		$('#errorEmailMessage').html("Required");
		flag=false;
	}else{
	    if(validateEmail(email)==0){
		  $("#errorEmailMessage").html("Invalid Email");
		  flag=false; 
	    }else{
			$('#errorEmailMessage').html("");
		}
	} 
	if(phone==""){
		$('#errorPhone').html('Required');
		flag=false; 
	}else if(isNaN(phone)){
		$('#errorPhone').html('Numbers only');
		flag=false; 
	}else{
		$('#errorPhone').html('');
	}
	if(flag==true){
		var imeiNumber=JSON.parse(localStorage["imeiNumber"]);
		$('#imgLoader').html('<img src="images/ajax-loader.gif"/>');
		$.ajax({
			type		:	'POST',
			url			:  	webServiceUrl+'submitwinner',
			dataType	: 	"json",
			data		:	{imeiNumber:imeiNumber,name:name,email:email,phone:phone},
			success: function(data){
				$('#imgLoader').html('');
				$('#won_box').hide();
				$('#sorry_message').show();
				$('#message_p').html('<p>You will receive an Email or call from </p><p>OMAR team for delivery of your prize.</p>');
				$('#message_p_arabic').html('<p>ستصلك رسالة أو مكالمة من فريق عمر لإستلام </p><p>جائزتك</p>');
			}
		});
	}
}	
function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
function validateEmail(emailValue){
var emailvalidation = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
   if(!emailvalidation.test(emailValue)){
     return 0;
    }else{
      return 1;
    }
}